﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SIGCBI.Entities;
using System.Data;
using System.Data.Objects;

namespace SIGCBI.Repository
{
    public interface ISexoRepository
    {
        List<SEXO> GetAllFromSexo();
        List<SEXO> GetAllFromSexoByDescripcion(string criterio);
        SEXO GetFromSexoById(Int32 id);

        void AddSexo(SEXO sexo);
        void UpdateSexo(SEXO sexo);
        void DeleteSexo(Int32 id);

        bool existeDuplicidad(string descripcion, Int32 id);
    }


    public class SexoRepository : MasterDataAccess, ISexoRepository
    {
        public List<SEXO> GetAllFromSexo()
        {
            var query = from p in Context.SEXOes
                        select p;
            ObjectContext.Refresh(RefreshMode.StoreWins, query);
            return query.ToList();
        }

        public List<SEXO> GetAllFromSexoByDescripcion(string criterio)
        {
            if (criterio != string.Empty)
            {
                var query = from p in Context.SEXOes
                            where p.Descripcion.ToUpper().Contains(criterio.ToUpper())
                            select p;
                ObjectContext.Refresh(RefreshMode.StoreWins, query);
                return query.ToList();
            }
            else
            {
                var query = from p in Context.SEXOes
                            select p;
                ObjectContext.Refresh(RefreshMode.StoreWins, query);
                return query.ToList();
            }
        }

        public SEXO GetFromSexoById(int id)
        {
            var query = from p in Context.SEXOes
                        where p.ID.Equals(id)
                        select p;
            return query.SingleOrDefault();
        }

        public void AddSexo(SEXO sexo)
        {
            Context.SEXOes.Add(sexo);
            Context.SaveChanges();
        }

        public void UpdateSexo(SEXO sexo)
        {
            Context.Entry(sexo).State = System.Data.EntityState.Modified;
            Context.SaveChanges();
        }

        public void DeleteSexo(int id)
        {
            var existe = Context.SEXOes.Where(p => p.ID.Equals(id)).SingleOrDefault();
            if (existe != null)
            {
                Context.SEXOes.Remove(existe);
                Context.SaveChanges();
            }
        }

        public bool existeDuplicidad(string descripcion, int id)
        {
            var query = from p in Context.SEXOes

                        where (p.Descripcion.ToUpper().CompareTo(descripcion.ToUpper()) == 0)
                        && p.ID!= id

                        select p;

            return query.Any();
        }
    }
}
